package com.zmm.type.custom.method.util;

import com.zmm.type.model.Category;
import com.zmm.type.vo.CategoryTreeNode;
import com.zmm.util.convert.ListUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义类目的工具类
 * @author 900045
 * @description:
 * @name CateUtil
 * @date By 2021-07-05 16:58:16
 */
public class CateUtil {

	public static List<CategoryTreeNode> getTreeNodes(List<Category> cateList) {
		if (ListUtil.isEmpty(cateList)) {
			return new ArrayList<>();
		}
		List<CategoryTreeNode> treeList = new ArrayList<>();
		//查询所有类目
		Map<Integer, CategoryTreeNode> cateMap = new HashMap<>(treeList.size());
		CategoryTreeNode node ;
		Integer level ;
		Integer parentId ;

		for (Category cate : cateList) {
			//二级
			if (cate.getFirstCategoryId() != 0 && cate.getSecondCategoryId() == 0) {
				parentId = cate.getFirstCategoryId();
				level = 2;
				//三级
			} else if (cate.getSecondCategoryId() != 0) {
				parentId = cate.getSecondCategoryId();
				level = 3;
			} else {
				parentId = 0;
				level = 1;
			}
			cate.setLevel(level);
			node = new CategoryTreeNode(cate.getCategoryId(), cate.getCategoryName(), parentId, level);
			cateMap.put(cate.getCategoryId(), node);
		}
		CategoryTreeNode parent = null;
		for (CategoryTreeNode treeNode : cateMap.values()) {
			if (treeNode.getLevel() == 1) {
				treeList.add(treeNode);
			} else {
				parent = cateMap.get(treeNode.getParentId());
				if (parent != null) {
					if (parent.getChildren() == null) {
						parent.setChildren(new ArrayList<>());
					}
					parent.getChildren().add(treeNode);
				}
			}
		}
		return treeList;
	}
}
